<template>
  <Dialog :title="dialogTitle" :outClose="closeModal" v-model="dialogVisible">
    <div class="wrap">
      <div class="detailHeader"
        v-if="(formType == 'detail' || formType == 'audit') && (infoStatus !== '未提交' && infoStatus !== '已驳回')">
        <div class="header flex">
          <div class="title flex items-center gap-5">
            <Icon :size="24" icon="ep:collection" />
            <div class="content text-2xl font-600"> {{ formInline.projectName }}</div>
          </div>
          <div class="status ml-auto mr-5 flex items-center gap-5 font-800">状态: <span class="text-[#0f40f5] text-2xl">{{
            infoStatus }}</span>
          </div>
        </div>
        <div class="info p-2 ml-13">
          <div class="mb-1">报价单编号：<span class=" font-fantasy ">{{ auditData.quoteNumber }}</span></div>
          <div>提报时间：<span>{{ formatDate(auditData.createTime) }}</span></div>
        </div>

      </div>
      <el-tabs v-model="activeTab" class="demo-tabs w-full" @tab-click="">
        <el-tab-pane label="报价单信息" name="info" class="w-full">
          <!-- no edit  只有待提交状态以及创建可以修改信息 -->
          <div v-if="(formType == 'detail' || formType == 'audit') && (infoStatus !== '未提交' && infoStatus !== '已驳回')"
            class="cards detail  w-full">
            <div class="quotationInfo">
              <el-card>
                <template #header>
                  <div class=" card-header">
                    <span>报价详情</span>
                  </div>
                </template>
                <div>
                  <vxe-toolbar>
                    <template #buttons>
                    </template>
                  </vxe-toolbar>
                  <!-- vxe-table 组件  文档：https://vxetable.cn/#/table/api?apiKey=table -->
                  <vxe-table :max-height="688" align="center" header-align="center" footer-align="left"
                    :edit-config="editConfig" footer-cell-class-name="footerCell"
                    :footer-span-method="footerColspanMethod" :footer-method="footerMethod_detail" :show-footer="true"
                    ref="tableRef" :data="tableData_detail">
                    <vxe-column field="seq" type="seq" title="序号" width="70" class="h-full">
                      <template #footer="{ row }">
                        <!-- footer item  -->
                        <div class="mid h-full">
                          <el-collapse v-model="row_activeNames" class="h-full">
                            <el-collapse-item v-for="(rc, k) in row.columns"
                              :class="k < (row.columns.length - 1) ? '' : 'hidden'" title="" :name="k + 1">
                              <div class=" w-full">
                                <div class=" inline-flex w-full">
                                  <div class="text mr-auto w-[220px] flex items-center"
                                    :class="rc.underLine ? 'line-through' : ''">
                                    {{ rc.text }}
                                  </div>
                                  <div v-for="(rowColumn, s) in rc.content" :key="s" class="flex-1 text-center"
                                    :class="s < (row.columns.length - 1) ? '' : 'none'">
                                    <span v-if="s < 2" class="">
                                      <span v-if="!rowColumn.prefix">￥{{ !rowColumn.prefix ?
                                        formatCurrency(rowColumn.price) :
                                        `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                      <span class=" font-800" v-if="rowColumn.prefix">{{
                                        !rowColumn.prefix ? formatCurrency(rowColumn.price) :
                                          `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                    </span>
                                    <span v-else>
                                      <span v-for="(f) in quotationDetail.finalQuotation">
                                        <span>￥
                                          {{ round(f.totalFinalDiscountPrice, 2) }}</span>
                                        <span class=" font-800">{{
                                          digitUppercase(round(f.totalFinalDiscountPrice, 2)) }}</span>
                                      </span>
                                    </span>
                                  </div>
                                </div>
                              </div>
                            </el-collapse-item>
                          </el-collapse>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="type" title="类别" :edit-render="{ enabled: false }">
                    </vxe-column>
                    <vxe-column field="productName" title="名称" :edit-render="{ enabled: false }">
                    </vxe-column>
                    <vxe-column field="salePrice" title="未税单价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span>{{ formatCurrency(row.salePrice) }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="count" title="数量" :edit-render="{ enabled: false }">
                    </vxe-column>
                    <vxe-column field="totalWithoutTax" title="未税总价(元)" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span>{{ formatCurrency(row.totalWithoutTax) }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="totalWithTax" title="含税总价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span>{{ formatCurrency(row.totalWithTax) }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="remark" show-overflow="tooltip" title="备注" width="256px"
                      :edit-render="{ enabled: false, isHover: true }">
                    </vxe-column>
                  </vxe-table>
                </div>
              </el-card>
            </div>
          </div>
          <div class="infoCard mt-2" v-if="formType !== 'create' && (infoStatus !== '未提交' && infoStatus !== '已驳回')">
            <el-card>
              <el-descriptions title="客户信息" :column="2">
                <el-descriptions-item class="font-800" label="客户名称:">{{ formInline_customer.name
                  }}</el-descriptions-item>
                <el-descriptions-item class="font-800" label="联系人:">{{ formInline_customer.contactName
                  }}</el-descriptions-item>
                <el-descriptions-item class="font-800" label="E-mail:">{{ formInline_customer.email
                  }}</el-descriptions-item>
                <el-descriptions-item class="font-800" label="联系电话:">{{ formInline_customer.mobile
                  }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
            <el-card class="mt-2">
              <el-descriptions title="我方信息" :column="2">
                <el-descriptions-item label="制作方名称:">{{ formInline.selfName }}</el-descriptions-item>
                <el-descriptions-item label="联系人:">{{ formInline.selfContactPerson }}</el-descriptions-item>
                <el-descriptions-item label="E-mail:">{{ formInline.selfEmail }}</el-descriptions-item>
                <el-descriptions-item label="联系电话:">{{ formInline.selfTel }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </div>
          <!-- ======================================================================================创建 -->
          <div v-if="formType == 'create'" class="cards w-full">
            <div class="baseInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>基础信息</span>
                  </div>
                </template>
                <el-form :disable="isDisabled" :inline="true" :model="formInline" class="">
                  <el-form-item label="项目信息">
                    <el-input v-model="formInline.projectName" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="customerInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>客户信息</span>
                  </div>
                </template>
                <el-form :inline="true" :model="formInline" class="">
                  <el-form-item label="客户名称" class="w-80">
                    <el-select @change="getCustomerInfo" v-model="formInline.customerId" :placeholder="hintText">
                      <el-option v-for="(customer, index) in customerList"
                        :label="(customer as any).name + '-' + (customer as any).contactName"
                        :value="(customer as any).id" :key="index" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="客户地址" class="w-100">
                    <el-input v-model="formInline_customer.detailAddress" :disabled="true" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="联系人">
                    <el-input v-model="formInline_customer.contactName" :disabled="false" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <el-input v-model="formInline_customer.mobile" :disabled="false" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="Email">
                    <el-input v-model="formInline_customer.email" :disabled="false" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="selfInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>我方信息</span>
                  </div>
                </template>
                <el-form :inline="true" :model="formInline" class="">
                  <el-form-item label="我方名称" class="w-80">
                    <el-input v-model="formInline.selfName" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="我方地址" class="w-100">
                    <el-input v-model="formInline.selfAddress" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="联系人">
                    <el-input v-model="formInline.selfContactPerson" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <el-input v-model="formInline.selfTel" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="Email">
                    <el-input v-model="formInline.selfEmail" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="quotationInfo">
              <el-card>
                <template #header>
                  <div class=" card-header">
                    <span>报价详情</span>
                  </div>
                </template>
                <div>
                  <vxe-toolbar>
                    <template #buttons>
                    </template>
                  </vxe-toolbar>
                  <!-- :row-config="{ height: rowHeight }" -->
                  <vxe-table @cell-dblclick="showDesc" v-if="tableData" :max-height="650" align="center"
                    :row-config="{ height: rowHeight }" header-align="center" footer-align="left"
                    :edit-config="editConfig" footer-cell-class-name="footerCell"
                    :footer-span-method="footerColspanMethod" :footer-method="footerMethod" :show-footer="true"
                    show-overflow ref="tableRef" @edit-activated="" @edit-closed="" :data="tableData">
                    <!-- :edit-config="{ trigger: 'click', mode: 'row' }" @edit-activated="editActivatedEvent" :column-config="{ resizable: true }" -->
                    <vxe-column field="seq" type="seq" width="70" title="序号" class="h-full">
                      <template #footer="{ row }">
                        <span v-if="row.index == 0" class="!text-xl ml-5" @click="insertEvent()">
                          <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                            <path fill="#409eff"
                              d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                            <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                          </svg>
                        </span>
                        <!-- footer child item 2 -->
                        <div class="mid h-full" v-if="row.index == 1">
                          <el-collapse v-model="row_activeNames" class="h-full">
                            <el-collapse-item v-for="(rc, k) in row.columns" :key="k" title="" :name="k + 1">
                              <div class=" w-full">
                                <div class=" inline-flex w-full">
                                  <div class="text mr-auto w-[220px] flex items-center"
                                    :class="rc.underLine ? 'line-through' : ''">
                                    <span class="!text-xl mr-2 " @click="() => addFinalTaxQuotation(row)"
                                      v-if="rc.icon?.add">
                                      <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"
                                        viewBox="0 0 32 32">
                                        <path fill="#409eff"
                                          d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                                        <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                                      </svg>
                                    </span>
                                    {{ rc.text }}
                                  </div>
                                  <div v-for="(rowColumn, s) in rc.content" :key="s" class="flex-1 text-center"
                                    :class="s < (row.columns.length - 1) ? '' : 'none'">
                                    <span v-if="s == 0 && k > 1">
                                      <!-- :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                        :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')" input 格式化 -->
                                      <el-input size="small" :disabled="rc.underLine" type="number" class="!w-28"
                                        v-model="quotationDetail.finalQuotation[k - 2].totalFinalDiscountPrice"
                                        :placeholder="hintText" clearable @change="getfinalQuotation">
                                        <template #prepend>￥</template>
                                      </el-input>
                                    </span>
                                    <span class="" v-else>
                                      <span v-if="!rowColumn.prefix">￥{{ !rowColumn.prefix ?
                                        formatCurrency(rowColumn.price) :
                                        `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                      <span class=" font-800" v-if="rowColumn.prefix">{{
                                        !rowColumn.prefix ? formatCurrency(rowColumn.price) :
                                          `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                    </span>
                                  </div>
                                  <span v-show="!rc.underLine" @click="(e) => deleteFinalTaxQuotation(e, row)"
                                    class="!text-xl mr-2 absolute right-18 cursor-pointer" v-if="rc.icon?.delete">
                                    <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                      xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                                      <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z"
                                        fill="#d81e06" p-id="1014"></path>
                                      <path
                                        d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                                        fill="#ffffff" p-id="1015"></path>
                                    </svg>
                                  </span>
                                </div>
                              </div>
                            </el-collapse-item>
                          </el-collapse>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="type" title="类别" :edit-render="{ placeholder: '请选择' }">
                      <template #default="{ row }">
                        <span>{{ formatRow(row) }}</span>
                      </template>
                      <template #edit="{ row }">
                        <vxe-select v-model="row.type" placeholder="请选择" clearable transfer @change="">
                          <vxe-option v-for="item in getQuoteType('QuoteDetailType')" :key="item.value"
                            :value="item.value" :label="item.label"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-column>
                    <vxe-column field="productName" title="名称" :edit-render="{ placeholder: '请输入' }">
                      <template #edit="{ row }">
                        <vxe-select placeholder="请选择" v-if="row.type == 1" v-model="row.productName" clearable transfer
                          @change="namechange(row)">
                          <vxe-option v-for="item in productNameOptions" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
                        </vxe-select>
                        <vxe-input v-else size="mini" placeholder="请输入" v-model="row.productName"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column width="220px" field="suggestedPrice" title="建议售价(元)" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span v-if="row.suggestedPrice">{{
                          formatCurrency(row.suggestedPrice)
                          }}</span>
                        <span v-else="">-</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="salePrice" title="未税单价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" @change="calcRow(row)" type="float" v-model="row.salePrice"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="count" title="数量" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" @change="calcRow(row)" type="number" v-model="row.count"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="totalWithoutTax" title="未税总价(元)" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        {{ formatCurrency(getTotal(row, false).totalWithoutTax) }}
                      </template>
                    </vxe-column>
                    <vxe-column field="taxRate" title="税率(%)" :edit-render="{ placeholder: '请选择' }">
                      <template #edit="{ row }">
                        <vxe-select placeholder="请选择" v-model="row.taxRate" clearable transfer @change="calcRow(row)">
                          <vxe-option v-for="item in getQuoteType('TAX_RATE')" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-column>
                    <vxe-column field="totalWithTax" title="含税总价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" @change="calcRow_totalWithTax(row)" type="float"
                          v-model="row.totalWithTax"></vxe-input>
                      </template>
                      <!-- <template #default="{ row }">
                        {{ formatCurrency(getTotal(row, true).totalWithTax) }}
                      </template> -->
                    </vxe-column>
                    <vxe-column field="memo" title="备注" width="256px" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-textarea v-model="row.remark" resize="vertical" show-overflow></vxe-textarea>
                      </template>
                    </vxe-column>
                    <vxe-column title="操作" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span @click="() => deleteRow(row)" class="!text-xl cursor-pointer">
                          <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                            <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#d81e06"
                              p-id="1014"></path>
                            <path
                              d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                              fill="#ffffff" p-id="1015"></path>
                          </svg>
                        </span>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </el-card>
            </div>
            <div class="memo" v-if="formType == 'create'">
              <el-card style="">
                <template #header>
                  <div class="card-header">
                    <span>备注信息</span>
                  </div>
                </template>
                <el-collapse v-model="activeNames" @change="">
                  <el-collapse-item title="" name="1">
                    <div class=" w-full">
                      <div class=" inline-flex"><span>1、交货期：合同签订后：</span> <el-input size="small" class="!w-20"
                          v-model="memo.deadLine" :placeholder="hintText" clearable />
                      </div>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="2">
                    <div class="w-full">
                      <span>2、付款方式：合同签订后：
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.deadLine"
                          :placeholder="hintText" clearable />
                        内预付款支付
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.prePay" :placeholder="hintText"
                          clearable />
                        、<el-select size="small" class="!w-40 ml-5" v-model="memo.payment.payType">
                          <el-option label="到货款支付" value="到货款支付"></el-option>
                          <el-option label="调试完成支付" value="调试完成支付"></el-option>
                        </el-select>
                        <el-input size="small" class="!w-48 mx-1 " v-model="memo.payment.afterPay"
                          :placeholder="hintText" clearable />
                        、终验支付
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.endPay" :placeholder="hintText"
                          clearable />
                      </span>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="3">
                    <div class="w-full">
                      <span>3、运输方式</span>
                      <el-select size="small" class="!w-40 ml-5" v-model="memo.delivery" :placeholder="hintText">
                        <el-option v-for="item in transportType" :key="item" :label="item.label" :value="item.value" />

                      </el-select>

                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full">
                      <span>4、质量保证：销售即日起，非人为造成的损坏或故障，质量保证期为 <el-input size="small" class="!w-20 mx-1"
                          v-model="memo.qualityGuarantee" :placeholder="hintText" clearable />
                      </span>

                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full flex items-center">
                      <span class="h-6">5、报价有效期：签字盖章后，<el-input size="small" class="!w-20 mr-3"
                          v-model="memo.quotationValidity" :placeholder="hintText" clearable />天内有效</span>
                      <span class="text-xl h-6 ml-2 cursor-pointer" @click="customizeShow = !customizeShow">
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                          <path fill="#409eff"
                            d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                          <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                        </svg>
                      </span>

                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4" v-show="customizeShow">
                    <div class="w-full">
                      <span><el-input size="small" class="!w-65 mr-3" v-model="memo.customize" :placeholder="hintText"
                          clearable /></span>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-card>

            </div>
          </div>
          <!-- ====================================================================================== 未提交状态，可以修改 -->
          <div v-if="formType == 'detail' && (infoStatus == '未提交' || infoStatus == '已驳回')" class="cards w-full">
            <div class="baseInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>基础信息</span>
                  </div>
                </template>
                <el-form :disable="isDisabled" :inline="true" :model="formInline" class="">
                  <el-form-item label="项目信息">
                    <el-input v-model="formInline.projectName" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="customerInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>客户信息</span>
                  </div>
                </template>
                <el-form :inline="true" :model="formInline" class="">
                  <el-form-item label="客户名称" class="w-80">
                    <el-select @change="getCustomerInfo" v-model="formInline.customerId" :placeholder="hintText">
                      <el-option v-for="(customer, index) in customerList"
                        :label="(customer as any).name + '-' + (customer as any).contactName"
                        :value="(customer as any).id" :key="index" />
                    </el-select>
                    <!-- <el-input v-model="formInline.customerName" :placeholder="hintText" clearable /> -->
                  </el-form-item>
                  <el-form-item label="客户地址" class="w-100">
                    <el-input v-model="formInline_customer.detailAddress" :disabled="true" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="联系人">
                    <el-input v-model="formInline_customer.contactName" :disabled="false" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <el-input v-model="formInline_customer.mobile" :disabled="false" :placeholder="hintText"
                      clearable />
                  </el-form-item>
                  <el-form-item label="Email">
                    <el-input v-model="formInline_customer.email" :disabled="false" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="selfInfo">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>我方信息</span>
                  </div>
                </template>
                <el-form :inline="true" :model="formInline" class="">
                  <el-form-item label="我方名称" class="w-80">
                    <el-input v-model="formInline.selfName" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="我方地址" class="w-100">
                    <el-input v-model="formInline.selfAddress" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="联系人">
                    <el-input v-model="formInline.selfContactPerson" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <el-input v-model="formInline.selfTel" :placeholder="hintText" clearable />
                  </el-form-item>
                  <el-form-item label="Email">
                    <el-input v-model="formInline.selfEmail" :placeholder="hintText" clearable />
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="quotationInfo">
              <el-card>
                <template #header>
                  <div class=" card-header">
                    <span>报价详情</span>
                  </div>
                </template>
                <div>
                  <vxe-toolbar>
                    <template #buttons>
                    </template>
                  </vxe-toolbar>
                  <vxe-table :row-config="{ height: rowHeight }" @cell-dblclick="showDesc" v-if="tableData"
                    :max-height="650" align="center" header-align="center" footer-align="left" :edit-config="editConfig"
                    footer-cell-class-name="footerCell" :footer-span-method="footerColspanMethod"
                    :footer-method="footerMethod" :show-footer="true" show-overflow ref="tableRef" :data="tableData">
                    <!-- :edit-config="{ trigger: 'click', mode: 'row' }" @edit-activated="editActivatedEvent" :column-config="{ resizable: true }" -->
                    <vxe-column field="seq" type="seq" title="序号" width="70" class="h-full">
                      <template #footer="{ row }">
                        <span v-if="row.index == 0" class="!text-xl ml-5" @click="insertEvent()">
                          <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                            <path fill="#409eff"
                              d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                            <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                          </svg>
                        </span>
                        <!-- footer child item 2 -->
                        <div class="mid h-full" v-if="row.index == 1">
                          <el-collapse v-model="row_activeNames" class="h-full">
                            <el-collapse-item v-for="(rc, k) in row.columns" :key="k" title="" :name="k + 1">
                              <div class=" w-full">
                                <div class=" inline-flex w-full">
                                  <div class="text mr-auto w-[220px] flex items-center"
                                    :class="rc.underLine ? 'line-through' : ''">
                                    <span class="!text-xl mr-2 " @click="() => addFinalTaxQuotation(row)"
                                      v-if="rc.icon?.add">
                                      <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"
                                        viewBox="0 0 32 32">
                                        <path fill="#409eff"
                                          d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                                        <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                                      </svg>
                                    </span>
                                    {{ rc.text }}
                                  </div>
                                  <div v-for="(rowColumn, s) in rc.content" :key="s" class="flex-1 text-center"
                                    :class="s < (row.columns.length - 1) ? '' : 'none'">
                                    <span v-if="s == 0 && k > 1">
                                      <!-- :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                        :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')" input 格式化 -->
                                      <el-input size="small" type="number" class="!w-28"
                                        v-if="quotationDetail.finalQuotation[k - 2]"
                                        v-model="quotationDetail.finalQuotation[k - 2].totalFinalDiscountPrice"
                                        :placeholder="hintText" :disabled="rc.underLine" clearable
                                        @change="getfinalQuotation">
                                        <template #prepend>￥</template>
                                      </el-input>
                                    </span>
                                    <span class="" v-else>
                                      <span v-if="!rowColumn.prefix">￥{{ !rowColumn.prefix ?
                                        formatCurrency(rowColumn.price) :
                                        `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                      <span class=" font-800" v-if="rowColumn.prefix">{{
                                        !rowColumn.prefix ? formatCurrency(rowColumn.price) :
                                          `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                    </span>
                                  </div>
                                  <span @click="(e) => deleteFinalTaxQuotation(e, row)" v-show="!rc.underLine"
                                    class="!text-xl mr-2 absolute right-18 cursor-pointer" v-if="rc.icon?.delete">
                                    <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                      xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                                      <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z"
                                        fill="#d81e06" p-id="1014"></path>
                                      <path
                                        d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                                        fill="#ffffff" p-id="1015"></path>
                                    </svg>
                                  </span>
                                </div>
                              </div>
                            </el-collapse-item>
                          </el-collapse>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="type" title="类别" :edit-render="{ placeholder: '请选择' }">
                      <template #default="{ row }">
                        <span>{{ formatRow(row) }}</span>
                      </template>
                      <template #edit="{ row }">
                        <vxe-select v-model="row.type" placeholder="请选择" clearable transfer @change="">
                          <vxe-option v-for="item in getQuoteType('QuoteDetailType')" :key="item.value"
                            :value="item.value" :label="item.label"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-column>
                    <vxe-column field="productName" title="名称" :edit-render="{ placeholder: '请输入' }">
                      <template #edit="{ row }">
                        <vxe-select placeholder="请选择" v-if="row.type == 1" v-model="row.productName" clearable transfer
                          @change="namechange(row)">
                          <vxe-option v-for="item in productNameOptions" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
                        </vxe-select>
                        <vxe-input placeholder="请输入" v-else size="mini" v-model="row.productName"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column width="220px" field="suggestedPrice" title="建议售价(元)" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span v-if="row.suggestedPrice">{{
                          formatCurrency(row.suggestedPrice)
                          }}</span>
                        <span v-else="">-</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="salePrice" title="未税单价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" type="number" v-model="row.salePrice" @change="calcRow(row)"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="count" title="数量" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" type="number" @change="calcRow(row)" v-model="row.count"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="totalWithoutTax" title="未税总价(元)" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        {{ formatCurrency(getTotal(row, false).totalWithoutTax) }}
                      </template>
                    </vxe-column>
                    <vxe-column field="taxRate" title="税率(%)" :edit-render="{ placeholder: '请选择' }">
                      <template #edit="{ row }">
                        <vxe-select placeholder="请选择" v-model="row.taxRate" clearable transfer @change="calcRow(row)">
                          <vxe-option v-for="item in getQuoteType('TAX_RATE')" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-column>
                    <vxe-column field="totalWithTax" title="含税总价" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-input size="mini" @change="calcRow_totalWithTax(row)" type="float"
                          v-model="row.totalWithTax"></vxe-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="memo" title="备注" width="256px" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <vxe-textarea v-model="row.remark" show-overflow resize="vertical"></vxe-textarea>
                      </template>
                    </vxe-column>
                    <vxe-column title="操作" :edit-render="{ enabled: false }">
                      <template #default="{ row }">
                        <span @click="() => deleteRow(row)" class="!text-xl cursor-pointer">
                          <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                            <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#d81e06"
                              p-id="1014"></path>
                            <path
                              d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                              fill="#ffffff" p-id="1015"></path>
                          </svg>
                        </span>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </el-card>
            </div>
            <div class="memo" v-if="(formType == 'create') || (formType == 'detail' && infoStatus == '未提交')">
              <el-card style="">
                <template #header>
                  <div class="card-header">
                    <span>备注信息</span>
                  </div>
                </template>
                <el-collapse v-model="activeNames" @change="">
                  <el-collapse-item title="" name="1">
                    <div class=" w-full">
                      <div class=" inline-flex"><span>1、交货期：合同签订后：</span> <el-input size="small" class="!w-20"
                          v-model="memo.deadLine" :placeholder="hintText" clearable />
                      </div>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="2">
                    <div class="w-full">
                      <span>2、付款方式：合同签订后：
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.deadLine"
                          :placeholder="hintText" clearable />
                        内预付款支付
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.prePay" :placeholder="hintText"
                          clearable />
                        、<el-select size="small" class="!w-40 ml-5" v-model="memo.payment.payType">
                          <el-option label="到货款支付" value="到货款支付"></el-option>
                          <el-option label="调试完成支付" value="调试完成支付"></el-option>
                        </el-select>
                        <el-input size="small" class="!w-48 mx-1 " v-model="memo.payment.afterPay"
                          :placeholder="hintText" clearable />
                        、终验支付
                        <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.endPay" :placeholder="hintText"
                          clearable />
                      </span>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="3">
                    <div class="w-full">
                      <span>3、运输方式</span>
                      <el-select size="small" class="!w-40 ml-5" v-model="memo.delivery" :placeholder="hintText">
                        <el-option v-for="item in transportType" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full">
                      <span>4、质量保证：销售即日起，非人为造成的损坏或故障，质量保证期为 <el-input size="small" class="!w-20 mx-1"
                          v-model="memo.qualityGuarantee" :placeholder="hintText" clearable />
                      </span>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full">
                      <span>5、报价有效期：签字盖章后，<el-input size="small" class="!w-20 mr-3" v-model="memo.quotationValidity"
                          :placeholder="hintText" clearable />天内有效</span>
                      <span class="text-xl h-6 ml-2 cursor-pointer" @click="customizeShow = !customizeShow">
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                          <path fill="#409eff"
                            d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                          <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                        </svg>
                      </span>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4" v-show="customizeShow">
                    <div class="w-full">
                      <span><el-input size="small" class="!w-65 mr-3" v-model="memo.customize" :placeholder="hintText"
                          clearable /></span>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-card>
            </div>
          </div>
          <!-- 如果是未提交状态，则查看详情的时候可以修改信息 -->
        </el-tab-pane>
        <el-tab-pane label="备注信息" v-if="(formType == 'detail' || formType == 'audit') && infoStatus !== '未提交'"
          name="memo" class="w-full">
          <div class="cards w-full">
            <div class="memo">
              <el-card style="">
                <template #header>
                  <div class="card-header">
                    <span>备注信息</span>
                  </div>
                </template>
                <el-collapse v-model="activeNames" @change="">
                  <el-collapse-item title="" name="1">
                    <div class=" w-full">
                      <div class=" inline-flex"><span>1、交货期：合同签订后：</span> <el-input
                          :disabled="formType == 'detail' || formType == 'audit'" size="small" class="!w-20 mx-1"
                          v-model="memo.deadLine" :placeholder="hintText" clearable />
                      </div>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="2">
                    <div class="w-full">
                      <span>2、付款方式：合同签订后：
                        <el-input :disabled="formType == 'detail' || formType == 'audit'" size="small"
                          class="!w-20 mx-1" v-model="memo.payment.deadLine" :placeholder="hintText" clearable />
                        内预付款支付
                        <el-input :disabled="formType == 'detail' || formType == 'audit'" size="small"
                          class="!w-20 mx-1" v-model="memo.payment.prePay" :placeholder="hintText" clearable />
                        、
                        <el-input :disabled="formType == 'detail' || formType == 'audit'" size="small"
                          class="!w-48 mx-1 " v-model="memo.payment.afterPay" :placeholder="hintText" clearable />
                        、终验支付
                        <el-input :disabled="formType == 'detail' || formType == 'audit'" size="small"
                          class="!w-20 mx-1" v-model="memo.payment.endPay" :placeholder="hintText" clearable />
                      </span>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="3">
                    <div class="w-full">
                      <span>3、运输方式</span>
                      <el-select :disabled="formType == 'detail' || formType == 'audit'" size="small" class="!w-40 ml-5"
                        v-model="memo.delivery" :placeholder="hintText">
                        <el-option v-for="item in transportType" :key="item" :label="item.label" :value="item.value" />
                      </el-select>

                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full">
                      <span>4、质量保证：销售即日起，非人为造成的损坏或故障，质量保证期为 <el-input size="small" class="!w-20 mx-1"
                          v-model="memo.qualityGuarantee" :disabled="formType == 'detail' || formType == 'audit'"
                          :placeholder="hintText" clearable />
                      </span>

                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4">
                    <div class="w-full">
                      <span>5、报价有效期：签字盖章后，<el-input :disabled="formType == 'detail' || formType == 'audit'" size="small"
                          class="!w-20 mr-3" v-model="memo.quotationValidity" :placeholder="hintText"
                          clearable />天有效</span>
                      <!-- <span class="text-xl h-6 ml-2 cursor-pointer" @click="customizeShow = !customizeShow">
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                          <path fill="#409eff"
                            d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                          <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                        </svg>
                      </span> -->
                    </div>
                  </el-collapse-item>
                  <el-collapse-item title="" name="4" v-show="customizeShow">
                    <div class="w-full">
                      <span><el-input size="small" class="!w-65 mr-3" v-model="memo.customize" :placeholder="hintText"
                          clearable /></span>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-card>

            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="签核流程" name="flow">
          <div class="signFlow">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span class="font-[15px] font-700">签核流程</span>
                </div>
              </template>
              <el-table :data="flowData" stripe style="width: 100%">
                <el-table-column header-align="center" align="center" type="index" label="序号" width="180" />
                <el-table-column header-align="center" align="center" prop="node" label="节点" />
                <el-table-column header-align="center" align="center" prop="operator" label="操作人" />
                <el-table-column :formatter="handleDate" header-align="center" align="center" prop="createTime"
                  label="操作时间" />
                <el-table-column header-align="center" align="center" prop="status" label="签核">
                  <template #default="scope">
                    <span>{{ scope.row.status == 0 ? '提交' : scope.row.status == 1 ? '同意' : '拒绝' }}</span>
                    <!-- <el-select size="small" v-model="NoForm.status[scope.$index].status"
                      :disabled="flowData[scope.$index].status !== 0" @change="(e) => handleChange(e, scope)">
                      <el-option v-for="item in opt1" :key="item.label" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select> -->
                  </template>
                </el-table-column>
                <el-table-column header-align="center" align="center" prop="advice" label="签核意见">
                  <template #default="scope">
                    <span>{{ scope.row.remark }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <el-button v-if="formType == 'create' || (formType == 'detail' && (infoStatus == '未提交' || infoStatus == '已驳回'))"
        @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button v-if="formType == 'create' || (infoStatus == '已驳回' || infoStatus == '未提交')" @click="submitQuote"
        type="primary" :disabled="formLoading">提 交</el-button>
      <!-- sign button -->
      <el-button v-hasPermi="['quote:quotation:audit']" v-if="formType == 'audit'" type="primary"
        :class="formType == 'audit' ? 'none' : ''" @click="prove" :disabled="formLoading">通 过</el-button>
      <el-button v-hasPermi="['quote:quotation:audit']" v-if="formType == 'audit'"
        :class="formType == 'audit' ? 'none' : ''" type="danger" @click="rejectThis">驳 回</el-button>
      <!-- sign button -->
      <!-- 签核通过，出现下载以及申请退回按钮 -->
      <el-button v-if="infoStatus == '已通过' && formType !== 'create'" type="primary"
        :class="formType == 'audit' ? 'none' : ''" @click="downloadQuote" :disabled="formLoading">下 载</el-button>
      <el-button v-if="infoStatus == '已通过' && formType !== 'create'" :class="formType == 'audit' ? 'none' : ''"
        type="danger" @click="applyBack">申请退回</el-button>
      <el-button v-if="infoStatus == '已退回' && formType !== 'create'" :class="formType == 'audit' ? 'none' : ''"
        type="danger" @click="reApply">重新发起</el-button>
      <el-button @click="closeModal">关 闭</el-button>
    </template>
  </Dialog>
  <vxe-drawer :before-hide-method="beforeHideMethod" mask-closable show-footer show-cancel-button v-model="showPopup"
    position="right" :title="curAdditive.selectedName + `-标准品描述`" width="400">
    <Editor :forbid="true" v-model="curAdditive.description" height="521px" />
  </vxe-drawer>
</template>

<script setup lang="ts">
import { digitUppercase, formatCurrency } from '@/utils/a_utilFunction';
import { VxeTableInstance } from 'vxe-table'
import type { VxeTablePropTypes } from 'vxe-table'
import { QuotationApi } from '@/api/quote/quotation'
import { CustomerApi } from '@/api/quote/customer'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { ProductApi } from '@/api/quote/product';
import { formatDate } from '@/utils/formatTime';
import { cloneDeep } from 'lodash-es';
import { useUserStore } from '@/store/modules/user'
import { round } from 'lodash-es'

interface RowVO {
  id: number;
  type: string[];
  name: string[];
  suggestedPrice: string;
  salePrice: string;
  count: string;
  totalWithoutTax: string;
  taxRate: string;
  totalWithTax: string;
  memo: string;
  finalQuotation: string;
}
// 40 10 合并一起计数
enum STATUS {
  "{10}" = '审批中',
  "{20}" = '已通过',
  "{30}" = '已驳回',
  "{40}" = '退回中',
  "{50}" = '已退回',
  "{0}" = '未提交'
}
// vxe-table 编辑前逻辑，后续或许用得上
// const beforeEdit = ({ row, rowIndex, column, columnIndex }) => {
//   return true  {beforeEditMethod: beforeEdit}
// 编辑之前的事件，返回true表示可以编辑，返回false表示不可编辑
// }
// const setEditRow = (row, fieldOrColumn) => {
//   console.log(row, fieldOrColumn)
// }

const editConfig = { trigger: 'click', mode: 'row', isHover: true }
const rowHeight = ref(50)

/** 报价单 表单 */
defineOptions({ name: 'QuotationForm' })
let userStore = useUserStore()
const { t } = useI18n() // 国际化
const customizeShow = ref(false)
//报价详情
let quotationDetail = ref({
  type: '',
  name: '',
  suggestedPrice: '',
  salePrice: '',
  count: '',
  totalWithoutTax: '',
  taxRate: '',
  totalWithTax: '',
  memo: '',
  finalQuotation: [{ totalFinalDiscountPrice: 0 }] as any,
})
//备注
let memo = ref({
  deadLine: '',
  payment: {
    deadLine: '',
    prePay: '',
    afterPay: '',
    endPay: '',
    payType: '到货款支付'
  },
  customize: '',
  delivery: '',
  qualityGuarantee: '',
  quotationValidity: ''
})
const tableData = ref<RowVO[]>([])
const tableData_detail = ref<RowVO[]>([])
let isDisabled = ref(false)
let totalItemsPrice = ref({
  totalNoTax: 0,
  totalWithTax: 0
})
let formInline_customer = ref({
  name: '',
  detailAddress: '',
  contactName: '',
  mobile: '',
  email: '',
})

let formInline = ref({
  projectName: '',
  customerId: undefined,
  selfName: '广州瑞沃斯视觉技术有限公司',
  selfAddress: '广州市黄埔区瑞祥路188号瑞松科技园C栋4楼',
  selfContactPerson: userStore.user.nickname,
  selfTel: '188888888888',
  selfEmail: 'ruiwosis@163.com',
})

let footerMethodData_base: any = [
  {
    type: 'add',
    index: 0
  },
  {
    type: 'column',
    index: 1,
    columns: [
      {
        text: '项目报价（未税）',
        content: [{ price: totalItemsPrice.value.totalNoTax }, { price: totalItemsPrice.value.totalNoTax, prefix: '大写' }],
      },
      {
        text: '含税总计报价',
        content: [{ price: totalItemsPrice.value.totalWithTax }, { price: totalItemsPrice.value.totalWithTax, prefix: '大写' }],
      },
      {
        text: '最终优惠含税总计报价',
        icon: { add: true },
      },
    ]
  }
]

let footerMethodData_detail_base = [
  {
    type: 'column',
    index: 1,
    columns: [
      {
        text: '项目报价（未税）',
        content: [{ price: totalItemsPrice.value.totalNoTax }, { price: totalItemsPrice.value.totalNoTax, prefix: '大写' }],
      },
      {
        text: '含税总计报价',
        content: [{ price: totalItemsPrice.value.totalWithTax }, { price: totalItemsPrice.value.totalWithTax, prefix: '大写' }],
      },
      {
        text: '最终优惠含税总计报价',
        content: [{ price: 0 }, { price: 0, prefix: '大写' }],
        icon: { delete: false }
      },
    ]
  }
]
const footerMethodData_detail = ref(footerMethodData_detail_base)
let infoStatus = ref('')
const flowData = ref([])
const tableRef = ref<VxeTableInstance<RowVO>>()
let $table
let activeTab = ref('info')
let tabsIndexs = ['1', '2', '3', '4']
let activeNames = ref(tabsIndexs)
let row_activeNames = ref(tabsIndexs)
let hintText = ref('请输入')
const products: any = ref([]);
const message = useMessage() // 消息弹窗
const customerList = ref([]) // 客户列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const submtJSON: any = ref({})
let auditData: any = ref({})
let openRes = ref({})
let productNameOptions: any = ref([])
let editFlag = ref(false)
let showPopup = ref(false)
const additive = reactive({
  description: {},
  selectedName: {},
})
const curAdditive = reactive({
  description: '',
  selectedName: '',
})

const beforeHideMethod = () => {}

const showDesc = ({ row }) => {
  if (row.type == 1 && row.productId) {
    // 选择标准品后，可以双击查看标准品描述
    showPopup.value = true
    curAdditive.description = additive.description[row._X_ROW_KEY]
    curAdditive.selectedName = additive.selectedName[row._X_ROW_KEY]
  }
}

const submitQuote = async () => {
  // 表示直接提交前，需要先保存报价单，且弹窗不关闭
  try {
    const data = await message.prompt('请输入提交报价单的备注信息', '报价单提交');
    if (data?.action !== 'confirm') return message.notify('已取消')
    // 直接提交，需要先调用保存报单价接口
    let submitQuoteNumber = await submitForm(false)
    if (typeof submitQuoteNumber !== 'string') {
      submitQuoteNumber = submtJSON.value.quoteNumber
    }
    const parmas = {
      quoteNumber: submitQuoteNumber,
      remark: data.value
    }
    const res = await QuotationApi.submitQuotation(parmas)
    if (res) {
      message.success('提交成功!')
      closeModal()
      dialogVisible.value = false
      emit('success')
    } else {
      message.error('网络错误，提交失败!')
    }
  } catch (error) {
    message.notify('已取消')
  }


}

// 根据字典获得数据
const getQuoteType = (dictType: string) => {
  let opts = getStrDictOptions(DICT_TYPE[dictType]);
  // console.log(opts)
  let optarr: any = [];
  opts.forEach((item) => {
    optarr.push(
      {
        label: item.label,
        value: item.value
      }
      // {
      // 这里是edit-render 是一个函数的时候的方式
      //   name: item.label,
      //   code: item.value
      // }
    )
  })
  return optarr
}

//计算出最终项目的两种价格
const calc2Price = () => {
  const { tableData } = $table.getTableData()
  // const {insertRecords}  = $table.getRecordset()
  totalItemsPrice.value.totalNoTax = 0
  totalItemsPrice.value.totalWithTax = 0
  tableData.forEach((item) => {
    totalItemsPrice.value.totalNoTax += parseFloat(item.totalWithoutTax)
    totalItemsPrice.value.totalWithTax += parseFloat(item.totalWithTax)
  })
  footerMethodData.value[1].columns![0].content![0].price = round(totalItemsPrice.value.totalNoTax, 2)
  footerMethodData.value[1].columns![0].content![1].price = round(totalItemsPrice.value.totalNoTax, 2)
  footerMethodData.value[1].columns![1].content![0].price = round(totalItemsPrice.value.totalWithTax)
  footerMethodData.value[1].columns![1].content![1].price = round(totalItemsPrice.value.totalWithTax)
}

//未税单价change事件
const calcRow = (row, isModified?: boolean = false) => {
  if (row.taxRate == '请点击输入' || row.salePrice == null || row.count == null) {
    return;
  }
  nextTick(() => {
    if (editFlag.value) {
      // 如果是修改总价，则不根据税率改变总价，而是只改变单价
      row.salePrice = round(row.totalWithTax / row.count / (1 + row.taxRate / 100), 2)
      editFlag.value = false
      // 修改含税总价后的，下一次税率的修改，不会触发重新计算含税总价，而是计算出未税单价
    } else {
      getTotal(row, true)
    }
    calc2Price()
  })
}

//含税总价change事件
const calcRow_totalWithTax = (row) => {
  // 如果taxRate 以及数量都为空，则提示计算出错！
  if (row.taxRate == '请点击输入' || row.count == null) {
    return;
  }
  //根据税率，输入的含税总价，以及数量，计算出未税单价，保留两位小数
  row.salePrice = round(row.totalWithTax / row.count / (1 + row.taxRate / 100), 2)
  calc2Price()
  editFlag.value = true
}

function getTotal(row: any, withTax?: boolean = false) {
  if (row.taxRate == '请点击输入' && withTax) return '/'
  if (!withTax) {
    row.totalWithoutTax = round(row.salePrice * row.count, 2)
  } else {
    row.totalWithTax = round(row.salePrice * row.count * (1 + (row.taxRate ?? 0) / 100), 2)
  }
  return row
}

const formatRow = (row) => {
  const item = getQuoteType('QuoteDetailType').find(item => item.value == row.type)
  return item ? item.label : row.type
}

function judgePrice(item) {
  let suggestedPrice;
  item.suggestedMinPrice = item.suggestedMinPrice == null ? 0 : item.suggestedMinPrice
  item.suggestedMaxPrice = item.suggestedMaxPrice == null ? 0 : item.suggestedMaxPrice
  if (item.suggestedMinPrice == 0 && item.suggestedMaxPrice == 0) {
    suggestedPrice = 0
  } else if (item.suggestedMinPrice == 0 && item.suggestedMaxPrice != 0) {
    suggestedPrice = item.suggestedMaxPrice
  }
  else if (item.suggestedMaxPrice == 0 && item.suggestedMinPrice != 0) {
    suggestedPrice = item.suggestedMinPrice
  } else {
    suggestedPrice = `${item.suggestedMinPrice}~${item.suggestedMaxPrice}`
  }
  return suggestedPrice
}

const activeHandler = ({ row }) => {
  if (row.type == 2) {
    // nameEditRender.name = 'VxeInput'
  } else {
    // nameEditRender.name = 'VxeSelect'
  }
}
const changeSalePrice = (e) => {
  let table = $table.getTableData()
  console.log(table)
}
const changeCount = () => { }
const changeVal = (val, row) => {
  let table = $table.getTableData()
  console.log(table)
}
const editClosedEvent = (row, rowIndex, $rowIndex, column, columnIndex, $columnIndex) => {
  // console.log(row, 'end=======')
}
const typeEditRender = reactive({
  name: 'VxeSelect',
  props: {
    multiple: false,
    placeholder: '请点击输入'
  },
  options: getQuoteType('QuoteDetailType'),
  optionProps: {
    label: 'name',
    value: 'code'
  },
  events: {
    async change({ row }) {
      // typeChange(row)
    }
  }
})

const namechange = async (row) => {
  let filterData = productNameOptions.value.filter((item) => item.value == row.productName)
  row.productName = filterData ? filterData[0].label : ''
  row.productId = filterData ? filterData[0].value : 0
  row.description = filterData ? filterData[0].description : '<p></p>'
  row.suggestedPrice = filterData ? judgePrice(filterData[0]) : '-'
  additive.description[row._X_ROW_KEY] = row.description
  additive.selectedName[row._X_ROW_KEY] = row.productName
  $table.reloadRow(row)
}

//关闭弹窗  初始化所有的数据
const closeModal = () => {
  // console.log(333000)
  dialogVisible.value = false
  openRes.value = {}
  activeTab.value = 'info'
  nextTick(() => {
    $table.remove()
    resetForm()
    footerMethodData.value = [
      {
        type: 'add',
        index: 0
      },
      {
        type: 'column',
        index: 1,
        columns: [
          {
            text: '项目报价（未税）',
            content: [{ price: totalItemsPrice.value.totalNoTax }, { price: totalItemsPrice.value.totalNoTax, prefix: '大写' }],
          },
          {
            text: '含税总计报价',
            content: [{ price: totalItemsPrice.value.totalWithTax }, { price: totalItemsPrice.value.totalWithTax, prefix: '大写' }],
          },
          {
            text: '新增最终优惠含税总计报价',
            icon: { add: true },
          },
        ]
      }
    ]
    footerMethodData_detail.value = [
      {
        type: 'column',
        index: 1,
        columns: [
          {
            text: '项目报价（未税）',
            content: [{ price: totalItemsPrice.value.totalNoTax }, { price: totalItemsPrice.value.totalNoTax, prefix: '大写' }],
          },
          {
            text: '含税总计报价',
            content: [{ price: totalItemsPrice.value.totalWithTax }, { price: totalItemsPrice.value.totalWithTax, prefix: '大写' }],
          },
          {
            text: '最终优惠含税总计报价',
            content: [{ price: 0 }, { price: 0, prefix: '大写' }],
            icon: { delete: false }
          },
        ]
      }
    ]
    addFlag.value = 0
    quotationDetail.value.finalQuotation = []
  })
  tableData.value = []
}

const downloadQuote = async () => {
  if (infoStatus.value == '已通过') {
    const res = await QuotationApi.exportQuotationPdf({ quoteNumber: auditData.value.quoteNumber });
    // console.log(res)
    if (res) {
      const blob = new Blob([res], { type: "application/vnd.ms-excel" })
      const url = URL.createObjectURL(blob)
      // window.open(url)
      const link = document.createElement('a')
      link.href = url
      link.download = `报价单-${auditData.value.quoteNumber}.pdf`
      link.click()
      URL.revokeObjectURL(url)
      message.success('下载中，请稍后查收！')
      dialogVisible.value = false
      emit('success')
      closeModal()
    }
  } else {
    message.error('该报价单未通过审核，无法下载！')
  }
}

const applyBack = async () => {
  const pms = {
    quoteNumber: auditData.value.quoteNumber,
    status: "1",
    remark: ''
  }
  const data = await message.prompt('请输入退回理由', '退回表单');
  pms.remark = data.value
  const res = await QuotationApi.applyQuotation(pms);
  // console.log(res)
  if (res) {
    message.success('退回成功！')
    dialogVisible.value = false
    emit('success')
  } else {
    message.error('error,未取消退回！请检查')
  }
}

const getStatusName = (status: number) => {
  return STATUS['{' + status + '}']
}

const handleDate = (row: any) => {
  return formatDate(row.createTime)
}

const fetchCustomerList = async () => {
  customerList.value = await CustomerApi.getAllCustomer() ?? [];
  $table = tableRef.value
}

const getCustomerInfo = () => {
  const customer: any = customerList.value.find(item => item.id === formInline.value.customerId);
  if (customer) {
    formInline_customer.value.name = customer.name;
    formInline_customer.value.detailAddress = customer.detailAddress;
    formInline_customer.value.contactName = customer.contactName;
    formInline_customer.value.mobile = customer.mobile;
    formInline_customer.value.email = customer.email;
  }
}

//同意
const prove = async () => {
  const data = await message.prompt('请输入审核意见', '通过审核');
  auditData.value.status = '1'
  auditData.value.remark = data.value
  const res = await QuotationApi.auditQuotation(auditData.value)
  if (res) {
    message.success('审核成功，您同意了该次审核！')
    dialogVisible.value = false
    emit('success')
    closeModal()
  }
}
//驳回
const rejectThis = async () => {
  const data = await message.prompt('请输入驳回意见', '驳回审核');
  auditData.value.remark = data.value
  auditData.value.status = '2'
  const res = await QuotationApi.auditQuotation(auditData.value)
  if (res) {
    message.success('审核成功，您驳回了该次审核！')
    dialogVisible.value = false
    emit('success')
    closeModal()
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  let userInfos = JSON.parse(localStorage.getItem('userInfo'))
  flowData.value = []
  activeTab.value = 'info'
  formInline.value = {
    projectName: '',
    customerId: undefined,
    selfName: '广州瑞沃斯视觉技术有限公司',
    selfAddress: '广州市黄埔区瑞祥路188号瑞松科技园C栋4楼',
    selfContactPerson: userInfos.nickname,
    selfTel: userInfos.mobile,
    selfEmail: userInfos.email,
  }
  formInline_customer.value = {
    name: '',
    detailAddress: '',
    contactName: '',
    mobile: '',
    email: '',
  }
  memo.value = {
    deadLine: '',
    payment: {
      deadLine: '',
      prePay: '',
      afterPay: '',
      endPay: '',
      payType: '到货款支付'
    },
    customize: '',
    delivery: '',
    qualityGuarantee: '',
    quotationValidity: ''
  },
    quotationDetail.value = {
      type: '',
      name: '',
      suggestedPrice: '',
      salePrice: '',
      count: '',
      totalWithoutTax: '',
      taxRate: '',
      totalWithTax: '',
      memo: '',
      finalQuotation: [{ totalFinalDiscountPrice: 0 }],
    }
  products.value = []
  totalItemsPrice.value = {
    totalNoTax: 0,
    totalWithTax: 0
  }

}

//computed  计算属性，用于计算每一项总金额
let totalTwo = computed(() => {
  let totalArr: any = [];
  for (let i = 0; i < products.value.length; i++) {
    totalArr.push({
      total: isNaN(Number(products.value[i].count) * Number(products.value[i].salePrice)) ? 0 : Number(products.value[i].count) * Number(products.value[i].salePrice),
      totalWithTax: isNaN(Number(products.value[i].count) * Number(products.value[i].salePrice) * (1 + (products.value[i].taxRate / 100))) ? 0 : (Number(products.value[i].count) * Number(products.value[i].salePrice) * (1 + (products.value[i].taxRate / 100)))
    });
  }
  return totalArr
})

const roleList = ref([
  { label: '前端', value: '1', disabled: false },
  { label: '后端', value: '2', disabled: false },
  { label: '项目经理', value: '3', disabled: false },
  { label: '设计师', value: '4', disabled: false },
  { label: '运维', value: '5', disabled: false }
])

const reApply = async () => {
  formLoading.value = true
  Object.assign(submtJSON.value, openRes.value);
  await QuotationApi.createQuotation(submtJSON.value as any)
  message.success('重新发起成功！！！')
  emit('success')
  closeModal()
  formLoading.value = false;
}
function keepFirstOccurrence(str, pattern) {
  const regex = new RegExp(pattern, 'g');
  return str.replace(regex, (match, index, original) => {
    // 如果是第一次出现，则不替换，否则替换为空字符串
    return index === 0 ? match : '';
  });
}

const resizeAllTextarea = () => {
  const textareaDoms = document.querySelectorAll('.vxe-table--body tbody tr[rowid] .vxe-textarea--inner')
  if (textareaDoms) {
    textareaDoms.forEach((textarea: any) => {
      textarea.style.height = '50px';
    })
  }
}
// 拖动说明那一栏，动态计算高度
function observerResize(newRow?, textareaDom?) {
  if (newRow) {
    setTimeout(() => {
      let textarea = document.querySelector(`.vxe-table--body tbody tr[rowid="${newRow['_X_ROW_KEY']}"] .vxe-textarea--inner`) as HTMLTextAreaElement;
      const resizeObserver = new ResizeObserver(debounce(() => {
        if (isFirstResize) {
          // 第一次渲染时不触发
          isFirstResize = false;
          return;
        }
        rowHeight.value = textarea.offsetHeight < 50 ? 50 : textarea.offsetHeight;
        if (rowHeight.value == 50) {
          // console.log(111)
          resizeAllTextarea()
        }
        console.log(`Textarea resized. Current size: ${textarea.offsetWidth}px by ${textarea.offsetHeight}px`);
      }, 333));
      // 监听 textarea 元素
      resizeObserver.observe(textarea!);
    }, 22)
  } else {
    setTimeout(() => {
      const resizeObserver = new ResizeObserver(debounce(() => {
        if (isFirstResize) {
          // 第一次渲染时不触发
          isFirstResize = false;
          return;
        }
        rowHeight.value = textareaDom.offsetHeight < 50 ? 50 : textareaDom.offsetHeight;
        if (rowHeight.value == 50) {
          resizeAllTextarea()
        }
        console.log(`Textarea resized. Current size: ${textareaDom.offsetWidth}px by ${textareaDom.offsetHeight}px`);
      }, 333));
      // 监听 textarea 元素
      resizeObserver.observe(textareaDom!);
    }, 22)
  }

}

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  nextTick(() => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    footerMethodData.value = [
      {
        type: 'add',
        index: 0
      },
      {
        type: 'column',
        index: 1,
        columns: [
          {
            text: '项目报价（未税）',
            content: [{ price: totalItemsPrice.value.totalNoTax }, { price: totalItemsPrice.value.totalNoTax, prefix: '大写' }],
          },
          {
            text: '含税总计报价',
            content: [{ price: totalItemsPrice.value.totalWithTax }, { price: totalItemsPrice.value.totalWithTax, prefix: '大写' }],
          },
          {
            text: '新增最终优惠含税总计报价',
            icon: { add: true },
          },
        ]
      }
    ]
    fetchCustomerList()
  })

  if (type == 'create') {
    resetForm()
  }
  else if (type == 'detail' || type == 'audit') {// 根据id查看详情
    // 打开弹窗，将第一个最终优惠价置空，避免影响其他报价单，
    nextTick(async () => {
      quotationDetail.value.finalQuotation = []
      let { id, quoteNumber, status } = row
      isDisabled.value = true
      infoStatus.value = getStatusName(status)
      const res = await QuotationApi.getQuotation(quoteNumber!, id!)
      openRes.value = res;
      flowData.value = res.auditProcessList;
      Object.assign(formInline.value, res)
      formInline.value.customerId = res.customerInfo.name
      Object.assign(formInline_customer.value, res.customerInfo)
      formInline_customer.value.contactName = res.customerContactPerson
      formInline_customer.value.mobile = res.customerTel
      formInline_customer.value.email = res.customerEmail
      let products1 = [] as any;
      res.products.forEach((item: any, index: number) => {
        products1.push({
          'productName': item.productName,
          'salePrice': item.salePrice,
          'count': item.count,
          'totalWithoutTax': round(item.totalPrice / (1 + item.taxRate / 100), 2),
          'totalWithTax': item.totalPrice,
          remark: item.remark,
          type: item.type == 1 ? '标准品' : '非标准品'
        })
      })
      tableData_detail.value = products1
      memo.value = res.memo
      if (memo.value.customize) {
        memo.value.customize = keepFirstOccurrence(memo.value.customize, /6、/g)
      }
      if (memo.value.customize !== '') {
        customizeShow.value = true
      }
      memo.value.payment = JSON.parse(memo.value.payment)
      if (infoStatus.value == '未提交') {
        let chineseRegex = /[\u4e00-\u9fa5]+/g;
        let numberRegex = /\d+/g;
        memo.value.payment.payType = memo.value.payment.afterPay.match(chineseRegex)?.join('')
        memo.value.payment.afterPay = memo.value.payment.afterPay.match(numberRegex)[0] > 100 ? memo.value.payment.afterPay.match(numberRegex)[0] : memo.value.payment.afterPay.match(numberRegex)[0] + '%'
      }

      addFinalTaxQuotation(res.finalPriceList, true)
      footerMethodData_detail.value[0].columns[0].content[0].price = res.totalProductPrice
      footerMethodData_detail.value[0].columns[0].content[1].price = res.totalProductPrice
      footerMethodData_detail.value[0].columns[1].content[0].price = res.totalPrice
      footerMethodData_detail.value[0].columns[1].content[1].price = res.totalPrice
      auditData.value.quoteNumber = res.quoteNumber
      auditData.value.createTime = res.createTime
      if (status == 0 || status == 30) {
        // 可修改
        isDisabled.value = false
        $table = tableRef.value
        products.value = [];
        res.products.forEach((item: any, index: number) => {
          products.value.push({
            'productName': item.productName,
            'salePrice': item.salePrice,
            'count': item.count,
            'totalWithoutTax': round(item.totalPrice / (1 + item.taxRate / 100)),
            'totalWithTax': item.totalPrice,
            taxRate: item.taxRate,
            remark: item.remark,
            type: item.type,
            suggestedPrice: judgePrice(item),
            suggestedMinPrice: item.suggestedMinPrice,
            suggestedMaxPrice: item.suggestedMaxPrice,
            productId: item.productId,
          })
        })
        tableData.value = products.value
        $table.reloadData(tableData.value).then(v => {
          const textareas = document.querySelectorAll(`.vxe-table--body tbody tr[rowid] .vxe-textarea--inner`)
          if (textareas) {
            textareas.forEach(textarea => {
              observerResize(undefined, textarea)
            })
          }
        })
      }
    })

  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

//提交表单
const submitForm = async (closeDialog?: boolean = true) => {
  // 校验表单
  // await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    Object.assign(submtJSON.value, quotationDetail.value, formInline.value)
    let { tableData } = $table.getTableData()
    products.value = tableData
    // console.log(tableData)
    products.value.forEach((item: any, index) => {
      if (item.type == 2) {
        if (item.productName === '') {
          message.error('产品名称不能为空！！！')
          return
        }
      }
      if (item.salePrice === '' || item.count === '' || item.taxRate === '' || item.type === '') {
        console.log(item)
        message.error('未税单价，数量，税率，类别均不能为空，请检查！！！')
        return
      }
      products.value[index].totalPrice = round(totalTwo.value[index].totalWithTax)
    })
    Object.assign(submtJSON.value, memo.value)
    products.value.forEach((item: any, index: number) => {
      products.value[index].sort = index + 1
    })
    submtJSON.value.products = products.value;
    let temp = transportType.value.filter((item: any) => {
      return item.code == memo.value.delivery
    })
    if (temp.length > 0) {
      memo.value.delivery = temp[0].label
    }
    let afterPay = ''
    let matchRes = memo.value.payment.afterPay!.match(/\d+/)
    if (matchRes) {
      if ((matchRes[0] as unknown as number) > 100) {
        //大于100 表示填的不是百分比
        afterPay = memo.value.payment.payType + matchRes[0]
      } else {
        afterPay = memo.value.payment.payType + matchRes[0] + '%'
      }
    } else {
      message.error('请输入正确的付款支付金额！')
    }
    memo.value.payment.afterPay = afterPay
    submtJSON.value.memo = memo.value
    if (customizeShow.value) {
      if (submtJSON.value.memo.customize) {
        submtJSON.value.memo.customize = keepFirstOccurrence(`6、` + submtJSON.value.memo.customize, /6、/g)
      }
    } else {
      submtJSON.value.memo.customize = ''
    }
    // 拼接上序号
    if (typeof formInline.value.customerId == "string") { // 如果等于undefined，说明是非用户id的字符串，也就是name
      let customerInfo: any = customerList.value.filter((item: any) => item.name == formInline.value.customerId)
      submtJSON.value.customerId = customerInfo[0].id
    }
    // 保留所有的优惠新增的话，需要传入一个数组，剪切 从第三个到倒数第二个的
    //最终优惠价等于 表格最终优惠价的对应的数组的倒数第二个price,如果没有添加则等于总价
    let finalPriceList: any = []
    if (footerMethodData.value[1].columns!.length > 3) {
      for (let i = 2; i < footerMethodData.value[1].columns!.length - 1; i++) {
        finalPriceList.push({
          "finalPrice": footerMethodData.value[1].columns![i].content![0].price,
          "finalPricePrefix": digitUppercase(footerMethodData.value[1].columns![i].content![0].price),
          "sort": i - 1
        })
      }
    }
    // finalPrice  最终优惠价字段
    let finalPrice = footerMethodData.value[1].columns!.length > 3 ? footerMethodData.value[1].columns![footerMethodData.value[1].columns!.length - 2].content![0].price : null
    submtJSON.value.finalPrice = finalPrice
    submtJSON.value.finalPriceList = finalPriceList
    if (finalPriceList.length == 0) { // 优惠价list为空数字，则清空优惠价字段
      submtJSON.value.finalPrice = ''
    }
    submtJSON.value.finalPricePrefix = digitUppercase(submtJSON.value.finalPrice)
    submtJSON.value.totalProductPrice = totalItemsPrice.value.totalNoTax
    submtJSON.value.totalProductPricePrefix = digitUppercase(submtJSON.value.totalProductPrice)
    submtJSON.value.totalPrice = round(totalItemsPrice.value.totalWithTax)
    submtJSON.value.totalPricePrefix = digitUppercase(submtJSON.value.totalPrice)
    submtJSON.value.customerContactPerson = formInline_customer.value.contactName
    submtJSON.value.customerTel = formInline_customer.value.mobile
    submtJSON.value.customerEmail = formInline_customer.value.email
    if (formType.value === 'create') {
      if (closeDialog) {
        await QuotationApi.createQuotation(submtJSON.value as any)
        message.success(t('common.createSuccess'))
        closeModal()
        dialogVisible.value = !closeDialog
        // 发送操作成功的事件
        emit('success')
        return false
      } else {
        // 表示创建后，就直接提交，不保存为草稿，不需要关闭弹窗
        return await QuotationApi.createQuotation(submtJSON.value as any)
      }

    } else if (formType.value === 'detail' && (infoStatus.value == '未提交' || infoStatus.value == '已驳回')) {
      if (closeDialog) {
        await QuotationApi.updateQuotation(submtJSON.value as any)
        message.success(t('common.updateSuccess'))
        closeModal()
        dialogVisible.value = !closeDialog
        // 发送操作成功的事件
        emit('success')
        return false
      } else {
        return await QuotationApi.updateQuotation(submtJSON.value as any)
      }
    }

  } finally {
    formLoading.value = false
  }
}

const footerMethodData = ref(footerMethodData_base)

watch(() => products.value, () => {
  // 最终统计总金额
  totalItemsPrice.value.totalNoTax = totalTwo.value.reduce((acc, cur) => acc + cur.total, 0)
  totalItemsPrice.value.totalWithTax = totalTwo.value.reduce((acc, cur) => acc + cur.totalWithTax, 0)
  footerMethodData.value[1].columns![0].content![0].price = totalItemsPrice.value.totalNoTax
  footerMethodData.value[1].columns![0].content![1].price = totalItemsPrice.value.totalNoTax
  footerMethodData.value[1].columns![1].content![0].price = round(Number(totalItemsPrice.value.totalWithTax))
  footerMethodData.value[1].columns![1].content![1].price = round(Number(totalItemsPrice.value.totalWithTax))
}, { deep: true })

const footerMethod_detail: VxeTablePropTypes.FooterMethod<RowVO> = () => {
  return footerMethodData_detail.value
}

const footerMethod: VxeTablePropTypes.FooterMethod<RowVO> = () => {
  return footerMethodData.value
}

//总是在最后一个元素前插入元素
function insertBeforeLast(arr, element) {
  if (arr.length < 2) {
    // 如果数组长度小于2，直接将元素添加到数组末尾
    arr.push(element);
  } else {
    // 插入到倒数第二个位置
    arr.splice(arr.length - 1, 0, element);
  }
  return arr;
}
//最终优惠含税总计报价输入事件
const getfinalQuotation = (val: string | number) => {
  if (val) {
    let index = addFlag.value - 1
    let dat =
      ("" + val) // 第一步：转成字符串
        .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
        .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
        .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
        .match(/^\d*(\.?\d{0,2})/g)![0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数

    quotationDetail.value.finalQuotation[index].totalFinalDiscountPrice = Number(dat)
    footerMethodData.value[1].columns![index + 2].content![0].price = Number(dat)
    footerMethodData.value[1].columns![index + 2].content![1].price = Number(dat)
  }
}

const changeUnderLine = (columns) => {
  // 将columns 中出了第一个，第二个和最后一个元素，其他的underLine都设置为true
  for (let i = 2; i < columns.length - 2; i++) {
    columns[i].underLine = true
  }
}

let addFlag = ref(0);

//新增最终优惠含税总计报价
const addFinalTaxQuotation = (row, isModified?: boolean = false) => {
  nextTick(() => {
    if (!isModified) {
      quotationDetail.value.finalQuotation.push({
        totalFinalDiscountPrice: 0
      })
      row.columns = insertBeforeLast(row.columns, {
        text: `最终优惠含税总计报价`,
        content: [{ price: '' }, { price: '', prefix: '大写' }],
        icon: { delete: true },
        underLine: false
      })
      addFlag.value++
      changeUnderLine(row.columns)
      footerMethodData.value[1].columns! = row.columns

      footerMethodData_detail.value[0].columns! = row.columns
    } else {
      addFlag.value = row.length
      let columns_new = cloneDeep(footerMethodData.value[1].columns!)
      let columns_new_details = cloneDeep(footerMethodData_detail.value[0].columns!)
      quotationDetail.value.finalQuotation = []
      row.forEach((r) => {
        quotationDetail.value.finalQuotation.push({
          totalFinalDiscountPrice: r.finalPrice
        })
        columns_new = insertBeforeLast(columns_new, {
          text: `最终优惠含税总计报价`,
          content: [{ price: r.finalPrice }, { price: r.finalPrice, prefix: '大写' }],
          icon: { delete: true },
          underLine: false,
        })
        columns_new_details = insertBeforeLast(columns_new_details, {
          text: `最终优惠含税总计报价`,
          content: [{ price: r.finalPrice }, { price: r.finalPrice, prefix: '大写' }],
          icon: { delete: true },
          underLine: false,
        })
      })
      changeUnderLine(columns_new)
      changeUnderLine(columns_new_details)
      // 如果是修改的话，展示出一条最终优惠价格，如果有的话, 修改，直接传入finalPrice == row
      footerMethodData.value[1].columns! = columns_new
      footerMethodData_detail.value[0].columns! = columns_new_details;
    }
  })
}

//找到包含class的父元素
function findParentWithClass(element, className) {
  // 确保传入的 element 是一个有效的 DOM 元素
  if (!element || !(element instanceof Element)) {
    throw new Error('Invalid DOM element');
  }

  // 向上查找直到根节点
  while (element) {
    if (element.classList && element.classList.contains(className)) {
      return element; // 返回找到的父元素
    }
    element = element.parentElement; // 继续向上查找
  }

  // 如果没有找到包含 className 的父元素，返回 null
  return null;
}

// 删除最终优惠
const deleteFinalTaxQuotation = (e, row) => {
  nextTick(() => {
    let ele = findParentWithClass(e.target, 'inline-flex');
    if (ele !== null) {
      let targetText = ele.childNodes[0].innerText;
      let index = row.columns.findIndex(v => {
        return v.text.includes(targetText)
      })
      if (index !== -1) {
        row.columns.splice(index, 1)
        addFlag.value--
        // console.log(row.columns, quotationDetail.value.finalQuotation)
        if (row.columns.length > 3) {
          let len = row.columns.length - 3; //这里的意思是如果新增了n个最终优惠，那么用row.columns.length - 3 == n, 
          quotationDetail.value.finalQuotation[len].totalFinalDiscountPrice = 0;
          row.columns[row.columns.length - 2].underLine = false
          let fitlerData = quotationDetail.value.finalQuotation.filter((v) => {
            return v.totalFinalDiscountPrice !== 0
          })
          // 然后过滤出不为零的数据，然后重新赋值给row.columns
          fitlerData.forEach((v, index) => {
            row.columns[index + 2].content![0].price = v.totalFinalDiscountPrice
            row.columns[index + 2].content![1].price = v.totalFinalDiscountPrice
          })
          footerMethodData.value[1].columns! = row.columns
          // 如果长度大于三，说明是有新增最终优惠的，那么吧最后一条数据的line-through去掉
        } else {

        }
        // Log(row)
      }
    }
  })
}

// 删除一行记录
const deleteRow = (row) => {
  message.confirm('您确认是否删除?').then(() => {
    if ($table) {
      $table.remove(row)
      calcRow(row)
      // 如果删除一行，那么products 也要删除这一行的数据
    }
  })
}

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}
let isFirstResize = true; // 标志位，检测是否是第一次渲染

//插入一条记录
const insertEvent = () => {
  // 这里需要到nextTick中去操作，否则会出现表格没有渲染完成就插入数据，导致表格没有渲染出来，并且会有离谱的bug
  nextTick(async () => {
    const $table = tableRef.value
    if ($table) {
      const record = {
        count: 1,
      }
      const { row: newRow } = await $table.insertAt(record, -1)
      await $table.setEditCell(newRow, 'type')
      observerResize(newRow)
    }
  })
}

// 表尾合并
const footerColspanMethod: VxeTablePropTypes.FooterSpanMethod = ({ $rowIndex, _columnIndex }) => {
  // Log($rowIndex, _columnIndex)
  if ($rowIndex === 0) {
    if (_columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 11
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
  if ($rowIndex === 1) {
    if (_columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 11
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

const updateRoleList = () => {
  const $table = tableRef.value
  if ($table) {
    // 获取表格中的全量数据
    const { fullData } = $table.getTableData()
    roleList.value.forEach(item => {
      if (item.value) {
        // 如果当前选项已经被选过，则禁用
        item.disabled = fullData.some(row => row.role === item.value)
      }
    })
  }
}

let transportType = ref([])

onMounted(async () => {
  //获取运输方式字典数据
  transportType.value = getQuoteType('TRANSPORT')
  // 获取标准品列表
  let res = await ProductApi.getProductPage({ pageNo: 1, pageSize: 100 })
  if (res.list) {
    res.list.forEach((item) => {
      productNameOptions.value.push({
        name: item.name,
        code: item.id,
        label: item.name,
        value: item.id,
        suggestedMinPrice: item.suggestedMinPrice,
        suggestedMaxPrice: item.suggestedMaxPrice,
        description: item.description,
      })
    })
  }
  let userInfo = await QuotationApi.getCurrentUserInfo()
  if (userInfo) {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }
})

nextTick(() => {
  updateRoleList()
})
</script>

<style lang="scss" scoped>
.infoCard {
  :deep(.el-descriptions__header) {
    padding-bottom: 12px;
    border-bottom: 1px solid #d0cece;
  }

  :deep(.el-descriptions__table) {
    width: 1000px;

    .el-descriptions__cell {
      width: 50%;
      font-weight: 700
    }
  }
}

.el-input {
  :deep(.el-input-group__prepend) {
    padding: 0 !important;
    background-color: transparent;
  }
}

.el-input-group__append button.el-button,
.el-input-group__prepend button.el-button {
  padding: 0 10px;
}

.el-input-group__append {
  border-left: none;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.el-input-group__prepend {
  border-right: none;
}

.mid {
  :deep(.el-collapse-item__wrap) {
    margin-left: 60px;
  }

  :deep(.el-collapse-item__content) {
    width: 100%;
    padding: 12px 5px !important;
  }
}

// :deep(.vxe-table--body-wrapper) {
//   max-height: 450px !important;
//   height: 202px !important;
// }

.card-header {
  span {
    font-weight: 700;
    font-size: 15px;
  }
}

.cards>div {
  &:nth-of-type(1) {
    margin-top: 15px;
  }

  margin-bottom: 30px;
}

.detail>div {
  margin-bottom: 0;
}

.el-collapse {
  border: 1px solid rgb(211, 207, 246);

  .el-collapse-item {
    &:last-child {
      margin-bottom: 0;
    }

    :deep(.el-collapse-item__header) {
      display: none !important;
    }

    :deep(.el-collapse-item__wrap) {
      background-color: transparent;
      display: flex !important;

      .el-collapse-item__content {
        padding: 8px 5px;
      }
    }

    &:nth-child(2n + 1) {
      background-color: rgb(230, 230, 230);
    }
  }
}
</style>
